<script setup lang="ts">
import { signInRqs } from '@/request/api'
import { useCommonStore } from '@/store/main'
import { Utils } from '@/common/utils.js'
import { sha256 } from 'js-sha256'
import type { FormInstance, FormRules } from 'element-plus'
import { INJECT_THEME_COLOR } from '@/common/provideType'

const THEME_COLOR = inject(INJECT_THEME_COLOR)
const $router = useRouter()
const $route = useRoute()
const $store = useCommonStore()
const vPreventReClick = inject('vPreventReClick')

// 表单相关
const formRef = ref<FormInstance>()
const successMessage = '登录成功'
const formData = reactive({
	userName: '',
	password: '',
})

const validateUserName = (rule: any, value: any, callback: any) => {
	if(!value) {
		return callback(new Error('请输入用戶名'));
	} else if(value.length < 2) {
		return callback(new Error('用戶名长度不能低于2位'));
	}
	callback();
}
const validatePassword = (rule: any, value: any, callback: any) => {
	if(!value) {
		return callback(new Error('请输入密码'));
	} else if(value.length < 6) {
		return callback(new Error('密码长度不能少于6位'));
	}
	callback();
}
// 表单校验
const rules = reactive<FormRules<typeof formData>>({
	userName: [
		{required: true, validator: validateUserName, trigger: 'blur'}
	],
	password: [
		{required: true, validator: validatePassword, trigger: 'blur'}
	]
})

// 确认登录
const signInFn = async (formEl: FormInstance | undefined) => {
	if(!formEl) return;
	await formEl.validate(async valid => {
		if(!valid) return
		const nonce = Utils.generateMixStrFn(8)
		const timeUTC = Math.ceil(Utils.getDate().getUTC / 1000)
		const hash = sha256.create()
		hash.update(`${formData.userName}_${formData.password}_${nonce}_${timeUTC}`)
		const signHex = hash.hex()
		console.log('signHex= ', signHex);
		const res = await signInRqs({
			user_name: formData.userName,
			nonce,
			ts: timeUTC,
			sign: signHex
		})

		if(res?.code === 0) {
			const data = res.data[0]
			const isNeedModifyPasswd = data.is_need_modify_passwd
			Utils.loginCountdown(Utils.getDate().getTime, data.ttl)
			$store.setUserInfo({
				userName: formData.userName,
				userType: data.user_type ,
				ttl: data.ttl,
				beginTime: Utils.getDate().getTime
			})
			// 正式开发环境，token在请求封装文件里设置（此处可删）
			$store.setToken(data.token);
			ElMessage({
				type: 'success',
				message: successMessage
			})
			$store.setUserStatus(isNeedModifyPasswd)
			if(isNeedModifyPasswd) {
				$router.push({path: '/setPassword'})
				return
			}

			if($route.query.redirect && $route.query.redirect !== '/login') {
				$router.push({path: `${$route.query.redirect}`})
			} else {
				$router.push({path: '/'})
			}
		}

		else ElMessage({
			type: 'error',
			message: res.msg
		})
	})
}

// 键盘按钮登录
const keyUpEnterFn = (formEl: FormInstance | undefined) => {
	if (!formEl) return
	signInFn(formEl)
}
</script>

<template>
	<div class="login">
		<div class="login-cont">
			<div class="title mb-20">{{ $store.systemInfo.systemNameCN }}</div>
			<el-form label-width="0" :model="formData" ref="formRef" :rules="rules">
				<el-form-item label="用户名" prop="userName">
					<el-input 
						v-model="formData.userName" 
						type="text" 
						maxlength="20" 
						placeholder="请输入用户名" 
						@keyup.enter="keyUpEnterFn(formRef)"
					/>
				</el-form-item>

				<el-form-item label="密码" prop="password">
					<el-input 
						v-model="formData.password" 
						maxlength="16" 
						show-password 
						placeholder="请输入登录密码" 
						@keyup.enter="keyUpEnterFn(formRef)"
					/>
				</el-form-item>

				<el-form-item>
					<el-button 
						v-preventReClick 
						:class="[`btn btn-${THEME_COLOR}`]"
						@click="signInFn(formRef)" 
					>
						登 录
					</el-button>
				</el-form-item>

				<el-form-item v-if="false">
					<div class="login-auxiliary-bar">
						<div>
							没有账号？<span class="color-theme ml-5">去注册</span>
						</div>
						<div>
							<span class="color-theme">忘记密码</span>
						</div>
					</div>
				</el-form-item>
			</el-form>
		</div>
    </div>
</template>

<style lang="scss" scoped>
.login {
	position: fixed;
	left: 0;
	top: 0;
	width: 100%;
	height: 100%;
	background-color: $color-f2;

	input::-webkit-input-placeholder {color: $color-ccc !important;}
	input::-moz-placeholder {color: $color-ccc !important;}
	:deep(.el-input__wrapper) {
		background-color: rgba(255, 255, 255, .6);
	}

	.login-cont {
		position:absolute;
		left:50%;
		top:50%;
		margin-left:-2.5rem;
		margin-top:-1.8rem;
		padding: .2rem .4rem;
		width: 5rem;
		// min-height:2.8rem;
		overflow: hidden;
		border-radius: .1rem;
		border: .01rem solid $color-white;
		box-shadow: -.02rem .02rem .03rem .02rem rgba(255, 255, 255, .4);
		background-image:-webkit-gradient(linear, left top, left bottom, from(rgba(255,255,255,0.35)), to(rgba(255,255,255,0.65)));
		background-image:linear-gradient(115deg, rgba(255,255,255,0.35) 0%, rgba(255,255,255,0.65) 100%);

		&:after {
			position: absolute;
			left: -.4rem;
			top: 0;
			z-index: -1;
			width: 12rem;
			height: 11.2rem;
			border-radius: 50%;
			background-color: rgba(0, 0, 0, .025);
			content: '';
		}
		
		.title {
			font-size: .22rem;
		}
		
		label {
			display: none;
			text-indent: -9999px;
		}

		.btn {
			width: 100%;
			height: .4rem;
		}

		.send-verification-code {
			position: absolute;
			right: .1rem;
			top: 0;
			color: $color-333;
			cursor: pointer;

			&:hover {
				color: $color-666;
			}
		}

		.icon-eye {
			position: absolute;
			right: 0;
			height: 100%;
			width: .03rem;
			cursor: pointer;
		}
	}

	.login-auxiliary-bar {
		display: -webkit-flex;
		display: flex;
		justify-content: space-between;
		width: 100%;
		font-size: .12rem;
	}
}
</style>